package com.fingard.dsp.bank.directbank.hfrcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.io.FileHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by F on 2020/2/4.
 */
public class HFRCB01Balance extends HFRCB01Base implements IBalance {
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {

        RetAts7506BalQry retAts7506BalQry = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts7506BalQry.writeStart();
        try {
            while (p_req7506.readRecord()) {
                RetAtsBalDetail detail = new RetAtsBalDetail();
                //非公有参数
                XmlTextWriter xmlWriter = new XmlTextWriter();
                HFRCB01Header header = new HFRCB01Header();
                header.reqTime =new Date();
                header.serialNo = getBatchID(header.reqTime);
                header.trsCode = "B2EACInfoQry";
                writeCommonHeader(xmlWriter,header);
                xmlWriter.writeStartElement("Body");
//                AcNo	账号	String(32)	M
                xmlWriter.writeElementString("AcNo", p_req7506.readedDetail.actNum);
                xmlWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlWriter.toXmlString(), false);
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSb = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                    if (tmpBkReader != null) {
                        String rsp_no = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                        String rsp_msg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                        if ("000000".equals(rsp_no)) {
                            if (tmpBkReader.read("/Message/Body/Map")){
                                detail.respCode = "0";
                                detail.actNum = tmpBkReader.readedXElement.getSingleTextNotNull("AcNo");
                                detail.actCur =convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("Currency"));
                                String acState  = tmpBkReader.readedXElement.getSingleTextNotNull("AcState");
                                if("0".equals(acState)){
                                    detail.acState ="2";
                                }else if("1".equals(acState)){
                                    detail.acState ="3";
                                }
                                detail.frozenBal =tmpBkReader.readedXElement.getSingleTextNotNull("FrznBalance");
                                detail.availBal =tmpBkReader.readedXElement.getSingleTextNotNull("AvabBalance");
                                detail.currBal =tmpBkReader.readedXElement.getSingleTextNotNull("Balance");
                                detail.yesterdayBal =tmpBkReader.readedXElement.getSingleTextNotNull("DBalance");
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = rsp_msg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSb.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = bankResult[1];
                }
                retAts7506BalQry.writeRetDetail(detail, p_req7506.isBatch);
            }
        } catch (Exception e) {
            retAts7506BalQry = new RetAts7506BalQry(p_req7506.reqHeader);
            retAts7506BalQry.writeStart();
            retAts7506BalQry.writeRespCode("-1");
            retAts7506BalQry.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts7506BalQry.writeEnd();
        return retAts7506BalQry;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        retAts.writeStart();
        Calendar tmpCalendarFrom = Calendar.getInstance();
        tmpCalendarFrom.setTime(p_req7505.getDateFrom());
        Calendar tmpCalendarTo = Calendar.getInstance();
        tmpCalendarTo.setTime(p_req7505.getDateTo());

        int tmpIntDateFrom = 0;
        int tmpIntDateTo = 0;
        while(tmpIntDateFrom<=tmpIntDateTo ) {
            Calendar tmpClndrStepTo = Calendar.getInstance();
            tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
            if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
            } else {
                tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
            }
            //查询历史余额
            qryHisBalByDate(Format.Date8Format.format(tmpCalendarFrom.getTime()),
                    Format.Date8Format.format(tmpClndrStepTo.getTime()), p_req7505, retAts);

            tmpCalendarFrom = tmpClndrStepTo;
            tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

        }
        if(retAts.getWrittenRdCount()==0){
            retAts.writeBatRespCode("-1");
            retAts.writeBatRespInfo("查询失败");
        }
        retAts.writeEnd();
        return retAts;
    }

     public void qryHisBalByDate(String dateFrom,String dateTo,Req7505HisBalQry p_req7505,RetAts7505HisBalQry retAts){
        try {
            RetAtsHisBalDetail detail = new RetAtsHisBalDetail();
            //非公有参数
            XmlTextWriter xmlWriter = new XmlTextWriter();
            HFRCB01Header header = new HFRCB01Header();
            header.reqTime =new Date();
            header.serialNo = getBatchID(header.reqTime);
            header.trsCode = "B2EACHistoryBalanceQry";
            writeCommonHeader(xmlWriter,header);
            xmlWriter.writeStartElement("Body");
//                AcNo	账号	String(32)	M
            xmlWriter.writeElementString("AcNo", p_req7505.actNum);
//                BeginDate	查询起始日期	String(8)	M	日期格式为：YYYYMMDD
            xmlWriter.writeElementString("BeginDate", p_req7505.dateFrom);
//                EndDate	查询结束日期	String(8)	M	结束日期必需大于起始日期
            xmlWriter.writeElementString("EndDate", p_req7505.dateTo);
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString(), false);
//            String[] bankResult = new String[]{"", ""};
//            bankResult[1] = FileHelper.readFileText("C:\\Users\\F\\Desktop\\tmp.xml", "gbk");
//            WriteBankLogStep3(bankResult[1]);
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSb = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                if (tmpBkReader != null) {
                    String rsp_no = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String rsp_msg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(rsp_no)) {
                        while(tmpBkReader.read("/Message/Body/List/Map")){
                            detail.actBal =tmpBkReader.readedXElement.getSingleTextNotNull("Balance");
                            detail.balDate =tmpBkReader.readedXElement.getSingleTextNotNull("Date");
                            retAts.writeRetDetail(detail);
                        }
                    } else {
                        throw new Exception(rsp_msg);
                    }
                } else {
                    throw new Exception( tmpSb.toString());
                }
            } else {
                throw new Exception(bankResult[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            WriteBankLogLn(String.format("针对账号：[%s]，起始日期：[%s]，结束日期:[%s]的历史余额查询失败",p_req7505.actNum,dateFrom,dateTo));
            WriteBankLogLn("报错原因："+e.getMessage());
        }
    }

}